﻿using AutoMapper;
using BW.EatRabbit.API.Application.Commands.Breeding;
using BW.EatRabbit.Domain;
using BW.EatRabbit.ErrorCode;
using BW.EatRabbit.Infrastructure.Interfaces;
using MediatR;

namespace BW.EatRabbit.API.Application.CommandHandlers.Breeding
{
    public class BreedingCreateCommandHandler : IRequestHandler<BreedingCreateCommand, APIResult<int>>
    {
        private readonly IBaseRepository<Breeding_Information> _breedinginformationRepository;
        private readonly IMapper _mapper;
        public BreedingCreateCommandHandler(IBaseRepository<Breeding_Information> breedinginformationRepository, IMapper mapper)
        {
            _breedinginformationRepository = breedinginformationRepository;
            _mapper = mapper;

        }
        public Task<APIResult<int>> Handle(BreedingCreateCommand request, CancellationToken cancellationToken)
        {
            APIResult<int> result = new APIResult<int>();
            result.Code = ResultCode.添加成功;
            result.Message = ResultCode.添加成功.ToString();

            var code = _mapper.Map<Breeding_Information>(request);
            if(code==null)
            {
                result.Code = ResultCode.添加失败;
                result.Message = "该养殖信息不能为空";
                return Task.FromResult(result);
            }
            var cpp = _breedinginformationRepository.GetAll().FirstOrDefault(x => x.BreedingId == code.BreedingId);
            if(cpp!=null)
            {
                result.Code = ResultCode.添加失败;
                result.Message = "该养殖信息已存在";
                return Task.FromResult(result);
            }
            code.Creator = request.UserNickname;
            _breedinginformationRepository.AddEntity(code);

            return Task.FromResult(result);
        }
    }
}
